package cn.ywang.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 发布一个远程服务
 *
 * @Auther: BeatificWang
 * @Date: 2018/11/25 23:21
 */
public class Server {

	// 线程池
	private static final ExecutorService executorService = Executors.newCachedThreadPool();

	public void publisher(final Object service, int port) {
		ServerSocket serverSocket = null;
		try {
			// 启动一个服务监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务端已启动成功");
			// 循环监听
			while (true) {
				Socket socket = serverSocket.accept();
				this.executorService.execute(new ProcessorHandler(socket, service));
			}
		} catch (Exception e) {
			throw new RuntimeException("服务端创建连接失败");
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
